package com.gullmall.product.exception;

import com.gullmall.common.exception.GullmallCodeEnum;
import com.gullmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.gullmall.product.controller")
public class GullMallExceptionAdvice {

    //数据校验的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap=new HashMap<>();
        //校验失败的字段
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(GullmallCodeEnum.VALID_EXCEPTION.getCode(),GullmallCodeEnum.VALID_EXCEPTION.getMsg()).put("data",errorMap);
    }

    //其他异常
    @ExceptionHandler(Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误",throwable);
        return R.error(GullmallCodeEnum.UNKONW_EXCEPTION.getCode(),GullmallCodeEnum.UNKONW_EXCEPTION.getMsg());
    }
}
